﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.ISerivces;
using DWF.Studio.Models;
using DWF.Studio.Project;
using DWF.Studio.Services;
using DWF.Studio.Share.Utils;
using Ookii.Dialogs.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfMessageBoxLibrary;

namespace DWF.Studio.Views
{
    /// <summary>
    /// UCtrlStartPage.xaml 的交互逻辑
    /// </summary>
    public partial class PageStart : Page
    {
        private IProjectRecordsService _projectRecordService = null;

        private IEnvironmentSerivce _environmentSerivce = null;

        private IAppService _appService = null;

        private IConfigService _configService = null;

        private string _startFilePath = "";
        public PageStart()
        {
            InitializeComponent();

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                init();
            }
        }

        private void init()
        {
            this._projectRecordService = new ProjectRecordsService();
            this._environmentSerivce = new EnvironmentSerivce();
            this._appService = AppService.Instance;
            this._configService = new ConfigService();

            GlobalActionHandler.ProjectRecordsRefresh += async (ea) =>
            {
                this.lbProjects.ItemsSource = await this._projectRecordService.GetRecentRecordsAsync();
            };

            startFile();
        }

        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (ProjectManager.Instance.CurrentProject != null)
            {
                btnBackProject.Visibility = Visibility.Visible;
            }
            else
            {
                btnBackProject.Visibility = Visibility.Hidden;
            }
            this.lbDemos.ItemsSource = (await this._projectRecordService.GetDemoRecordsAsync()).Take(10);
            GlobalActionHandler.ProjectRecordsRefresh?.Invoke(EventArgs.Empty);
           
            var osinof = _environmentSerivce.GetCurrentOSInfo();
            this.tbkOS.Text = osinof.Caption;
            this.tbkNFw.Text = _environmentSerivce.GetFrameworkVersion();
        }

        private void LbProjectItem_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                var projectRecord = this.lbProjects.SelectedItem as ProjectRecord;
                if (projectRecord != null )
                {
                    var path = System.IO.Path.Combine(projectRecord.ProjectPath, StaticResource.ProjectFile);
                    var oldPath = System.IO.Path.Combine(projectRecord.ProjectPath, StaticResource.OldProjectFile);
                    if (ProjectManager.Instance.CurrentProject != null)
                    {
                        GlobalActionHandler.BackStartPage?.Invoke(new TagEventArgs<bool>(false));
                        GlobalActionHandler.ProjectClosing?.Invoke(EventArgs.Empty);
                    }
                    if (FileHelper.CheckFileExisting(path))
                    {
                        WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("PageStart_Msg_LoadProject"), App.Current.MainWindow);//显示loading窗体
                        GlobalActionHandler.ProjectOpen?.Invoke(new TagEventArgs<string>(path));
                        WindowLoading.CloseWindow();//关闭loading窗体
                    }
                    else if (FileHelper.CheckFileExisting(oldPath))
                    {
                        WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("PageStart_Msg_LoadProject"), App.Current.MainWindow);//显示loading窗体
                        GlobalActionHandler.ProjectOpen?.Invoke(new TagEventArgs<string>(oldPath));
                        WindowLoading.CloseWindow();//关闭loading窗体
                    }
                    else
                    {
                        var msgProperties = new WpfMessageBoxProperties()
                        {
                            Button = MessageBoxButton.YesNo,
                            ButtonYesText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Yes"),
                            ButtonNoText = LocalizationProvider.GetLocalizedString("MessageBox_Button_No"),
                            Image = MessageBoxImage.Question,
                            Text = LocalizationProvider.GetLocalizedString("PageStart_MsgBox_Msg_ProjectFileNotExisting"),
                            Title = LocalizationProvider.GetLocalizedString("PageStart_MsgBox_Caption_Delete"),
                        };

                        Window owner = Window.GetWindow(this);
                        MessageBoxResult dlgResult = WpfMessageBox.Show(owner, ref msgProperties);

                        if (dlgResult == MessageBoxResult.Yes)
                        {
                            this._projectRecordService.DelectRecord(projectRecord.ProjectPath);
                            GlobalActionHandler.ProjectRecordsRefresh?.Invoke(EventArgs.Empty);
                        }
                    }
                }
            }
        }

        private void LbDemoItem_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                var projectRecord = this.lbDemos.SelectedItem as ProjectRecord;
                if (projectRecord != null)
                {
                    var path = System.IO.Path.Combine(projectRecord.ProjectPath, StaticResource.ProjectFile);
                    var oldPath = System.IO.Path.Combine(projectRecord.ProjectPath, StaticResource.OldProjectFile);
                    if (ProjectManager.Instance.CurrentProject != null)
                    {
                        GlobalActionHandler.BackStartPage?.Invoke(new TagEventArgs<bool>(false));
                        GlobalActionHandler.ProjectClosing?.Invoke(EventArgs.Empty);
                    }
                    if (FileHelper.CheckFileExisting(path))
                    {
                        WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("PageStart_Msg_LoadProject"), App.Current.MainWindow);//显示loading窗体
                        GlobalActionHandler.ProjectOpen?.Invoke(new TagEventArgs<string>(path));
                        WindowLoading.CloseWindow();//关闭loading窗体
                    }
                    else if (FileHelper.CheckFileExisting(oldPath))
                    {
                        WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("PageStart_Msg_LoadProject"), App.Current.MainWindow);//显示loading窗体
                        GlobalActionHandler.ProjectOpen?.Invoke(new TagEventArgs<string>(oldPath));
                        WindowLoading.CloseWindow();//关闭loading窗体
                    }
                }
            }
        }

        /// <summary>
        /// 新建Sequence工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdNewProjectSequence_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            WindowCreateProject projectDialog = new WindowCreateProject();
            projectDialog.SetDefaultProjectName("Sequence");
            projectDialog.Owner = App.Current.MainWindow;
            var result = projectDialog.ShowDialog();
            var path = projectDialog.SelectedPath;
            var descri = projectDialog.Description;
            var platform = projectDialog.TargetPlatform;
            var wfLanguage = projectDialog.WorkflowLanguage;
            if (result == true)
            {
                WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_NewProject_Sequence"), App.Current.MainWindow);//显示loading窗体
                if (wfLanguage == StaticResource.WorkflowLanguage_vb)
                {
                    GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateSequence_vb));
                }
                else if (wfLanguage == StaticResource.WorkflowLanguage_cs)
                {
                    GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateSequence_cs));
                }
                WindowLoading.CloseWindow();//关闭loading窗体
            }
        }

        /// <summary>
        /// 新建Flowchart工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdNewProjectFlowchart_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            WindowCreateProject projectDialog = new WindowCreateProject();
            projectDialog.SetDefaultProjectName("Flowchart");
            projectDialog.Owner = App.Current.MainWindow;
            var result = projectDialog.ShowDialog();
            var path = projectDialog.SelectedPath;
            var descri = projectDialog.Description;
            var platform = projectDialog.TargetPlatform;
            var wfLanguage = projectDialog.WorkflowLanguage;
            if (result == true)
            {
                if (ProjectManager.Instance.CurrentProject != null)
                {
                    GlobalActionHandler.BackStartPage?.Invoke(new TagEventArgs<bool>(false));
                    GlobalActionHandler.ProjectClosing?.Invoke(EventArgs.Empty);
                }
                WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_NewProject_Flowchart"), App.Current.MainWindow);//显示loading窗体
                if (wfLanguage == StaticResource.WorkflowLanguage_vb)
                {
                    GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateFlowchart_vb));
                }
                else if (wfLanguage == StaticResource.WorkflowLanguage_cs)
                {
                    GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateFlowchart_cs));
                }
                WindowLoading.CloseWindow();//关闭loading窗体
            }
        }

        /// <summary>
        /// 打开工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdOpenProject_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var projectDialog = new VistaOpenFileDialog();
            projectDialog.Title = LocalizationProvider.GetLocalizedString("OpenFileDialog_Title_OpenProject");
            projectDialog.Multiselect = false;
            projectDialog.Filter = LocalizationProvider.GetLocalizedString("OpenFileDialog_Filter_OpenProject");
            var result = projectDialog.ShowDialog(App.Current.MainWindow);
            var path = projectDialog.FileName;
            var ext = System.IO.Path.GetExtension(path);
            if (ext != StaticResource.OldProjectFile && ext != StaticResource.ProjectFile)
            {
                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.OK,
                    ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                    Image = MessageBoxImage.Error,
                    Text = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_FileNotFound"),//WinMain_MsgBox_Msg_ProjectFileTypeError
                    Title = LocalizationProvider.GetLocalizedString("App_MsgBox_Caption_Exception"),
                };
                Window owner = Window.GetWindow(this);
                WpfMessageBox.Show(owner, ref msgProperties);
                return;
            }
            if (result == true)
            {
                if (ProjectManager.Instance.CurrentProject != null)
                {
                    GlobalActionHandler.BackStartPage?.Invoke(new TagEventArgs<bool>(false));
                    GlobalActionHandler.ProjectClosing?.Invoke(EventArgs.Empty);
                }
                WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_LoadProject"), App.Current.MainWindow);//显示loading窗体
                GlobalActionHandler.ProjectOpen?.Invoke(new TagEventArgs<string>(path));
                WindowLoading.CloseWindow();//关闭loading窗体
            }
        }

        private void BtnOperations_Click(object sender, RoutedEventArgs e)
        {
            var mainwin = Window.GetWindow(this);
            WindowAbout window = new WindowAbout();
            window.Owner = mainwin;
            window.ShowDialog();
        }

        private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
        {
            var projectRecord = this.lbProjects.SelectedItem as ProjectRecord;

            if (projectRecord != null)
            {
                this._projectRecordService.DelectRecord(projectRecord.ProjectPath);
                GlobalActionHandler.ProjectRecordsRefresh?.Invoke(EventArgs.Empty);
            }
            else
            {
                var item = ((ListBoxItem)lbProjects.ContainerFromElement((System.Windows.Controls.Button)sender)).Content as ProjectRecord;
                if (item != null)
                {
                    this._projectRecordService.DelectRecord(item.ProjectPath);
                    GlobalActionHandler.ProjectRecordsRefresh?.Invoke(EventArgs.Empty);
                }
            }
        }


        private void BtnClearProjecRecords_Click(object sender, RoutedEventArgs e)
        {
            this._projectRecordService.ClearRecords();
            GlobalActionHandler.ProjectRecordsRefresh?.Invoke(EventArgs.Empty);
        }

        private void BtnMoreDemos_Click(object sender, RoutedEventArgs e)
        {
            var path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, StaticResource.HelpDocumnet, StaticResource.Examples);
            System.Diagnostics.Process.Start("Explorer.exe", path);
        }

        private void imageInossem_MouseLeftButtonUp(object sender, RoutedEventArgs e)
        {
            var config = _configService.LoadAppConfig();
            if (!String.IsNullOrWhiteSpace(config.OfficialWebsite))
            {
                System.Diagnostics.Process.Start(config.OfficialWebsite);
            }
        }

        private void imageProcessgo_MouseLeftButtonUp(object sender, RoutedEventArgs e)
        {
            var config = _configService.LoadAppConfig();
            if (!String.IsNullOrWhiteSpace(config.ProcessgoWebsite))
            {
                System.Diagnostics.Process.Start(config.ProcessgoWebsite);
            }
        }
        private void startFile()
        {
            int lineArgs = 0;
            foreach (var i in Environment.GetCommandLineArgs())
            {
                if (lineArgs > 0)
                {
                    _startFilePath += i.ToString();
                }
                lineArgs++;
            }
        }
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemOpenFolder_Click(object sender, RoutedEventArgs e)
        {
            var projectRecord = this.lbProjects.SelectedItem as ProjectRecord;
            if (projectRecord != null)
            {
                var path = projectRecord.ProjectPath;
                if (!String.IsNullOrWhiteSpace(path))
                {
                    System.Diagnostics.Process.Start("Explorer.exe", path);
                }
            }
            else
            {
                var item = ((ListBoxItem)lbProjects.ContainerFromElement((System.Windows.Controls.Button)sender)).Content as ProjectRecord;
                if (item != null)
                {
                    var path = item.ProjectPath;
                    if (!String.IsNullOrWhiteSpace(path))
                    {
                        System.Diagnostics.Process.Start("Explorer.exe", path);
                    }
                }
            }
        }

        private void rbtnRecentProject_Click(object sender, RoutedEventArgs e)
        {
            this.recentProject.Visibility = Visibility.Visible;
            this.btnClearProjecRecords.Visibility = Visibility.Visible;
            this.imgClear.Visibility = Visibility.Visible;
            this.demoProject.Visibility = Visibility.Hidden;
            this.btnMoreDemos.Visibility = Visibility.Hidden;
        }

        private void rbtnDemoProject_Click(object sender, RoutedEventArgs e)
        {
            this.recentProject.Visibility = Visibility.Hidden;
            this.btnClearProjecRecords.Visibility = Visibility.Hidden;
            this.imgClear.Visibility = Visibility.Hidden;
            this.demoProject.Visibility = Visibility.Visible;
            this.btnMoreDemos.Visibility = Visibility.Visible;
        }

        private void btnSystemInformation_Click(object sender, RoutedEventArgs e)
        {
            var mainwin = Window.GetWindow(this);
            WindowLicense window = new WindowLicense();
            window.Owner = mainwin;
            window.ShowDialog();
        }

        private void btnBackProject_Click(object sender, RoutedEventArgs e)
        {
            GlobalActionHandler.BackStartPage?.Invoke(new TagEventArgs<bool>(false));
        }
    }
}

